#!/usr/bin/env python

'''
Thought i'd give you a suggestion to your start.sh. 
I didnt have a lot of time, so i could not figure out how you pass the arguments to your other 
modules, so i made this example debug friendly. Hope some of this can be of help.

//Are Hansen
'''

import argparse
import os
import subprocess
import sys
try:
    import modules.postfix_creds
except ImportError, err:
    print err
    sys.exit(1)
try:
    import modules.open_relay
except ImportError, err:
    print err
    sys.exit(1)


__author__ = '@awhitehatter'
__appname__ = sys.argv[0].split('/')[-1].split('.')[0]
__version__ = '0.1-1'
__modifier__ = '@Bifrozt_Dev'



def parse_args():
    """Defining command line arguents. """
    parser = argparse.ArgumentParser(
                description='{0} - {1} - v{2}'.format(__appname__, __author__, __version__)
                )

    mail_port = 25
    listen_to = '0.0.0.0'

    define = parser.add_argument_group('- Honeypot definitions')
    define.add_argument(
                       '-i',
                       action='store', 
                       metavar='<ip address>',
                       default=listen_to,
                       nargs=1, 
                       help='The IP address to listen on (default: {0})'.format(listen_to)
                       )
    define.add_argument(
                       '-p',
                       action='store', 
                       metavar='<port>', 
                       default=mail_port,
                       nargs=1, 
                       help='The port to listen on (default: {0})'.format(mail_port)
                       )
    define.add_argument(
                       '-s',
                       action='store', 
                       metavar='mailserver', 
                       help='The name that will show up as the mail server name. (I.E: -s mailserver)',
                       nargs=1,
                       required=True
                       )
    define.add_argument(
                       '-t',
                       action='store',
                       choices=['open_relay', 'postfix_creds'], 
                       help='Honeypot type',
                       required=True
                       )

    excopt = parser.add_argument_group('- Run time options')
    # Mutually exclusive, so only one of these are accepted, while one of them MUST be used
    runopt = excopt.add_mutually_exclusive_group(required=True)
    runopt.add_argument(
                       '-D',
                       dest='debug',
                       help='Do not daemonize the process, run in forground',
                       action='store_true'
                       )
    runopt.add_argument(
                       '-B',
                       dest='daemon',
                       help='Daemonize the process, run in backgound',
                       action='store_true'
                       )

    args = parser.parse_args()
    return args


def daemonize(run_cmd):
    """Executes a system command, returns the exit code from that command. """
    subp = subprocess.Popen(
            run_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
            )

    xcode = subp.wait()
    return xcode


def check_args(args):
    """Parse all the arguments and do some checking before trying to run stuffz. """
    # Executing user UID
    euid = os.getegid()
    #set the IP address variables
    print 'DEBUG:', '\nargs.t:', args.t, '\nargs.i:', args.i, '\nargs.p:', args.p, '\nargs.s:', args.s

    # Check for UID 0
    if euid != 0:
        print '[Error]: Your UID is {0}, only root with UID 0 can run {1}'.format(euid, __appname__)
        sys.exit(1)

    #create log directory (thanks @Bifrozt_Dev)
    if not os.path.isdir('logs'):
            os.mkdir('logs')

    # This code block is executed if '-D' is used
    if args.debug:
        #call server type module, based on parsed arguments
        if 'postfix_creds' in args.t:
            print 'DEBUG: modules.postfix_creds.pfserver()'

        if 'open_relay' in args.t:
            print 'DEBUG: modules.open_relay.or_module()'

    # This code block is executed if '-B' is used
    if args.daemon:
        #call server type module, based on parsed arguments
        if 'postfix_creds' in args.t:
            print 'DEBUG: modules.postfix_creds.pfserver()'

            execute_cmd = daemonize('_INSERT_COMMAND_AND_ARGUMENTS_HERE_')
            
            if execute_cmd == 0:
                print 'DEBUG: Yay! Its running as a daemon'
                sys.exit(0)

            if execute_cmd != 0:
                print 'DEBUG: ...Something went very wrong...'
                sys.exit(1)

        if 'open_relay' in args.t:
            print 'DEBUG: modules.open_relay.or_module()'

            execute_cmd = daemonize('_INSERT_COMMAND_AND_ARGUMENTS_HERE_')

            if execute_cmd == 0:
                print 'DEBUG: Yay! Its running as a daemon'
                sys.exit(0)

            if execute_cmd != 0:
                print 'DEBUG: ...Something went very wrong...'
                sys.exit(1)


def main():
    args = parse_args()
    check_args(args)


if __name__ == '__main__':
    main()
